import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

export function init({
  canvas = null,
  clearColor = 0xb9d3ff,
  addAxesHelper = true,
  addController = true,
  isOrthographicCamera = true,
}={}) {
  const scene = new THREE.Scene();

  const W = canvas ? canvas.clientWidth : 800;
  const H = canvas ? canvas.clientHeight : 800;
  const D = 4000
  const render = canvas
    ? new THREE.WebGLRenderer({ canvas })
    : new THREE.WebGLRenderer();
  render.setSize(W, H);
  if (!canvas) {
    canvas = render.domElement;
  }

  if (null !== clearColor) {
    render.setClearColor(clearColor, 1);
  }

  let camera;
  
  if (isOrthographicCamera) {
    camera = new THREE.OrthographicCamera(
      -W / 2,
      W / 2,
      H / 2,
      -H / 2,
      -D/2,
      D/2
    );
    camera.position.set(200, 300, 200);
  } else {
    camera = new THREE.PerspectiveCamera(60, W / H, 1, D*25);
  }
  camera.lookAt(scene.position);

  function customRender() {
    render.render(scene, camera);
  }

  if (addAxesHelper) {
    scene.add(new THREE.AxesHelper(H));
  }
  if (addController) {
    const controller = new OrbitControls(camera, canvas);
    controller.addEventListener("change", customRender);
  }
  return { scene, camera, render, renderFn: customRender, canvas };
}
